#include "mainwindow.hpp"

MainWindow::MainWindow()
{
    centralWidget = new QWidget(this);

    contentScene = new QGraphicsScene();
    contentView = new QGraphicsView(contentScene);
    imagePanel = new QListWidget();

    createActions();
    createMenus();
    createToolBars();
    createStatusBar();

    readSettings();

    generateChildsBtn = new QPushButton(tr("Generate childs"));
    addChildBtn = new QPushButton(tr("Add child"));

    //contentLayout = new QVBoxLayout();
    //contentLayout->addWidget(contentScene);
    //contentView->setLayout(contentLayout);

    panelLayout = new QVBoxLayout();
    panelLayout->addWidget(addChildBtn);
    panelLayout->addWidget(imagePanel);
    panelLayout->addWidget(generateChildsBtn);

    mainLayout = new QHBoxLayout();
    mainLayout->addLayout(panelLayout);
    mainLayout->addWidget(contentView, 4);
    centralWidget->setLayout(mainLayout);

    setCentralWidget(centralWidget);
    setCurrentFile("");
    setUnifiedTitleAndToolBarOnMac(true);

    //TODO: dorobit connecty
    //connect(textEdit->document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));
    //connect(textEdit->document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));
    //connect(textEdit->document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified()));

}

MainWindow::~MainWindow(){
    //TODO: write me
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

void MainWindow::newFile()
{
    if (maybeSave()) {
        contentScene->clear();
        setCurrentFile("");
    }
}

void MainWindow::open(){
    if (maybeSave()) {
	QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath());
	if (!fileName.isEmpty()) {
	    QImage image(fileName);
	    if (image.isNull()) {
		QMessageBox::information(this, tr("Image problem"), tr("Cannot load %1.").arg(fileName));
	    } else {
		contentScene->addPixmap(QPixmap::fromImage(image));
		scaleFactor = 1.0;

		printAct->setEnabled(true);
		fitToWindowAct->setEnabled(true);
		updateActions();

		if (!fitToWindowAct->isChecked()) contentView->adjustSize();
	    }
	}
    }
}

void MainWindow::print(){
#ifndef QT_NO_PRINTER
    QPrintDialog dialog(&printer, this);
    if (dialog.exec()) {
	QPainter painter(&printer);
	QRect rect = painter.viewport();
	//QSize size = scene->pixmap()->size(); //takato neni, keby to nebolo dobre, tak sa to prerobi
	//size.scale(rect.size(), Qt::KeepAspectRatio);
	//painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
	//painter.setWindow(contentScene->sceneRect());
	contentScene->render(&painter);
    }
#endif
}

void MainWindow::zoomIn(){
    scaleImage(1.25);
}

void MainWindow::zoomOut(){
    scaleImage(0.8);
}

void MainWindow::normalSize(){
    contentView->adjustSize();
    scaleFactor = 1.0;
}

void MainWindow::fitToWindow()
{
//TODO: dat scroll area ako central widget pre view
    ////bool fitToWindow = fitToWindowAct->isChecked();
    ////scrollArea->setWidgetResizable(fitToWindow);
    ////if (!fitToWindow) {
        ////normalSize();
    ////}
    ////updateActions();
}

bool MainWindow::save()
{
    if (curFile.isEmpty()) {
        return saveAs();
    } else {
        return saveFile(curFile);
    }
}

bool MainWindow::saveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this);
    if (fileName.isEmpty())
        return false;

    return saveFile(fileName);
}

void MainWindow::about()
{
   QMessageBox::about(this, tr("About Mul project"), tr("Authors: xbulka00, xstane00"));
}

//void MainWindow::documentWasModified()
//{
    //setWindowModified(textEdit->document()->isModified());
//}

void MainWindow::createActions()
{
    newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
    newAct->setShortcuts(QKeySequence::New);
    newAct->setStatusTip(tr("Create a new file"));
    connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

    openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip(tr("Open an existing file"));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    printAct = new QAction(tr("&Print..."), this);
    printAct->setShortcut(QKeySequence::Print);
    printAct->setEnabled(false);
    connect(printAct, SIGNAL(triggered()), this, SLOT(print()));

    saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
    saveAct->setShortcuts(QKeySequence::Save);
    saveAct->setStatusTip(tr("Save the document to disk"));
    connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));

    saveAsAct = new QAction(tr("Save &As..."), this);
    saveAsAct->setShortcuts(QKeySequence::SaveAs);
    saveAsAct->setStatusTip(tr("Save the document under a new name"));
    connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));

    exitAct = new QAction(tr("E&xit"), this);
    exitAct->setShortcuts(QKeySequence::Quit);

    exitAct->setStatusTip(tr("Exit the application"));
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

    zoomInAct = new QAction(QIcon(":/trolltech/dialogs/qprintpreviewdialog/images/zoom-in-32.png"), 
				tr("Zoom &In (25%)"), this);
    zoomInAct->setShortcut(QKeySequence::ZoomIn);
    zoomInAct->setEnabled(false);
    connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));

    zoomOutAct = new QAction(QIcon(":/trolltech/dialogs/qprintpreviewdialog/images/zoom-out-32.png"),
				tr("Zoom &Out (25%)"), this);
    zoomOutAct->setShortcut(QKeySequence::ZoomOut);
    zoomOutAct->setEnabled(false);
    connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));

    normalSizeAct = new QAction(QIcon(":/trolltech/dialogs/qprintpreviewdialog/images/view-page-one-32.png"), 
				tr("&Normal Size"), this);
    normalSizeAct->setShortcut(tr("Ctrl+0"));
    normalSizeAct->setEnabled(false);
    connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));

    fitToWindowAct = new QAction(QIcon(":/trolltech/dialogs/qprintpreviewdialog/images/fit-page-32.png"),
				tr("&Fit to Window"), this);
    fitToWindowAct->setEnabled(false);
    fitToWindowAct->setCheckable(true);
    fitToWindowAct->setShortcut(tr("Ctrl+1"));
    connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));

    cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
    cutAct->setShortcuts(QKeySequence::Cut);
    cutAct->setStatusTip(tr("Cut the current selection's contents to the "
                            "clipboard"));
    //connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));

    copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
    copyAct->setShortcuts(QKeySequence::Copy);
    copyAct->setStatusTip(tr("Copy the current selection's contents to the "
                             "clipboard"));
    //connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));

    pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
    pasteAct->setShortcuts(QKeySequence::Paste);
    pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
                              "selection"));
    //connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));

    actToASCIIAct = new QAction(QIcon(":/images/asciiart.png"), tr("To ASCII"), this);
    actToASCIIAct->setStatusTip(tr("Convert current image to ASCII art form"));
    //connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    videoFromThisAct = new QAction(QIcon(":/images/video.png"), tr("To video"), this);
    videoFromThisAct->setStatusTip(tr("Generate video from current image"));
    //connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    generateNewAct = new QAction(QIcon(":/images/genetic.png"), tr("Create new"), this);
    generateNewAct->setStatusTip(tr("Generate new image"));
    connect(generateNewAct, SIGNAL(triggered()), this, SLOT(createGenetics()));

    aboutAct = new QAction(tr("&About"), this);
    aboutAct->setStatusTip(tr("Show the application's About box"));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

    aboutQtAct = new QAction(tr("About &Qt"), this);
    aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
    connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

    cutAct->setEnabled(false);
    copyAct->setEnabled(false);
    //connect(textEdit, SIGNAL(copyAvailable(bool)), cutAct, SLOT(setEnabled(bool)));
    //connect(textEdit, SIGNAL(copyAvailable(bool)), copyAct, SLOT(setEnabled(bool)));
}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAct);
    fileMenu->addAction(openAct);
    fileMenu->addAction(saveAct);
    fileMenu->addAction(saveAsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(printAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));
    editMenu->addAction(cutAct);
    editMenu->addAction(copyAct);
    editMenu->addAction(pasteAct);

    menuBar()->addSeparator();

    viewMenu = menuBar()->addMenu(tr("&View"));
    viewMenu->addAction(zoomInAct);
    viewMenu->addAction(zoomOutAct);
    viewMenu->addAction(normalSizeAct);
    viewMenu->addSeparator();
    viewMenu->addAction(fitToWindowAct);

    menuBar()->addSeparator();

    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
    helpMenu->addAction(aboutQtAct);
}

void MainWindow::createToolBars()
{
    fileToolBar = addToolBar(tr("File"));
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);

    editToolBar = addToolBar(tr("Edit"));
    editToolBar->addAction(cutAct);
    editToolBar->addAction(copyAct);
    editToolBar->addAction(pasteAct);

    viewToolBar = addToolBar(tr("View"));
    viewToolBar->addAction(zoomInAct);
    viewToolBar->addAction(zoomOutAct);
    viewToolBar->addAction(normalSizeAct);
    viewToolBar->addAction(fitToWindowAct);

    graphicsToolBar = addToolBar(tr("Images"));
    graphicsToolBar->addAction(actToASCIIAct);
    graphicsToolBar->addAction(generateNewAct);

    videoToolBar = addToolBar(tr("Video"));
    videoToolBar->addAction(videoFromThisAct);
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void MainWindow::readSettings()
{
    QSettings settings("Trolltech", "Application Example");
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(400, 400)).toSize();
    resize(size);
    move(pos);
}

void MainWindow::writeSettings()
{
    QSettings settings("Trolltech", "Application Example");
    settings.setValue("pos", pos());
    settings.setValue("size", size());
}

bool MainWindow::maybeSave()
{
    //if (textEdit->document()->isModified()) {
        //QMessageBox::StandardButton ret;
        //ret = QMessageBox::warning(this, tr("Application"),
                     //tr("The document has been modified.\n"
                        //"Do you want to save your changes?"),
                     //QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        //if (ret == QMessageBox::Save)
            //return save();
        //else if (ret == QMessageBox::Cancel)
            //return false;
    //}
    return true;
}

bool MainWindow::saveFile(const QString &fileName)
{
    //QFile file(fileName);
    //if (!file.open(QFile::WriteOnly | QFile::Text)) {
        //QMessageBox::warning(this, tr("Application"),
                             //tr("Cannot write file %1:\n%2.")
                             //.arg(fileName)
                             //.arg(file.errorString()));
        //return false;
    //}

    //QTextStream out(&file);
//#ifndef QT_NO_CURSOR
    //QApplication::setOverrideCursor(Qt::WaitCursor);
//#endif
    //out << textEdit->toPlainText();
//#ifndef QT_NO_CURSOR
    //QApplication::restoreOverrideCursor();
//#endif

    //setCurrentFile(fileName);
    //statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

void MainWindow::updateActions(){
    zoomInAct->setEnabled(!fitToWindowAct->isChecked());
    zoomOutAct->setEnabled(!fitToWindowAct->isChecked());
    normalSizeAct->setEnabled(!fitToWindowAct->isChecked());
}

void MainWindow::scaleImage(double factor){ //TODO: dorobit
    scaleFactor *= factor;
    //imageLabel->resize(scaleFactor * imageLabel->pixmap()->size());

    //adjustScrollBar(scrollArea->horizontalScrollBar(), factor);
    //adjustScrollBar(scrollArea->verticalScrollBar(), factor);

    zoomInAct->setEnabled(scaleFactor < 3.0);
    zoomOutAct->setEnabled(scaleFactor > 0.333);
}

void MainWindow::adjustScrollBar(QScrollBar *scrollBar, double factor){ //TODO: az bude scrollbar potom odkomentovat
    //scrollBar->setValue(int(factor * scrollBar->value() + ((factor - 1) * scrollBar->pageStep()/2)));
}

void MainWindow::setCurrentFile(const QString &fileName)
{
    curFile = fileName;
    ////////textEdit->document()->setModified(false);
    setWindowModified(false);

    QString shownName = curFile;
    if (curFile.isEmpty())
        shownName = "untitled";
    setWindowFilePath(shownName);
}

QString MainWindow::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}

void MainWindow::createGenetics(){
    Genetic *newImg = new Genetic();
    this->contentScene->addPath(*newImg);
    
}
